package com.wenzheng.mybatisplus.util;

import org.springframework.beans.*;

import java.beans.*;
import java.util.*;

/**
 * BeanUtils 扩展类
 * @author tdf
 * @date 2019-10-20 15:53
 **/
public class BeanUtils {
	/**
	 * 忽略null 值复制copy
	 * @param src 源
	 * @param target 目标
	 */
	public static <S, T> T copyPropertiesIgnoreNull(S src, T target) {
		org.springframework.beans.BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
		return target;
	}

	/**
	 * 获取为null的属性
	 * @param source 源
	 * @return String[]
	 */
	private static String[] getNullPropertyNames(Object source) {
		BeanWrapper src = new BeanWrapperImpl(source);
		PropertyDescriptor[] pds = src.getPropertyDescriptors();
		HashSet<String> emptyNames = new HashSet<>(4);
		for (PropertyDescriptor pd : pds) {
			Object srcValue = src.getPropertyValue(pd.getName());
			if ("".equals(srcValue)) {
				emptyNames.add(pd.getName());
			}
		}

		return emptyNames.toArray(new String[0]);
	}

}
